package com.beta.cat.utils.sequence.builder;

import com.beta.cat.service.RedissonService;
import com.beta.cat.utils.sequence.range.impl.redis.RedisSeqRangeMgr;
import com.beta.cat.utils.sequence.seq.Sequence;
import com.beta.cat.utils.sequence.seq.impl.DefaultRangeSequence;

/**
 * 基于redis取步长，序列号生成器构建者
 * Created by fctao on 2018/5/30.
 */
public class RedisSeqBuilder implements SeqBuilder {

    /**
     * redis服务
     */
    private RedissonService redissonService;
    /**
     * 业务名称[必选]
     */
    private String bizName;
    /**
     * 获取range步长[可选，默认：1000]
     */
    private int step = 1000;

    /**
     * 序列号分配起始值[可选：默认：0]
     */
    private long stepStart = 0;

    @Override
    public Sequence build() {
        //利用Redis获取区间管理器
        RedisSeqRangeMgr redisSeqRangeMgr = new RedisSeqRangeMgr();
        redisSeqRangeMgr.setRedissonService(this.redissonService);
        redisSeqRangeMgr.setStep(this.step);
        redisSeqRangeMgr.setStepStart(stepStart);
        redisSeqRangeMgr.init();
        //构建序列号生成器
        DefaultRangeSequence sequence = new DefaultRangeSequence();
        sequence.setName(this.bizName);
        sequence.setSeqRangeMgr(redisSeqRangeMgr);
        return sequence;
    }

    public static RedisSeqBuilder create() {
        RedisSeqBuilder builder = new RedisSeqBuilder();
        return builder;
    }

    public RedisSeqBuilder redissonService(RedissonService redissonService) {
        this.redissonService = redissonService;
        return this;
    }

    /**
     * 获取步长[可选，默认：1000]，也就是一次获取多个序列号在内存中，减少与redis的交互，提高性能。
     */
    public RedisSeqBuilder step(int step) {
        this.step = step;
        return this;
    }

    /**
     * 指定业务名称，便于隔离每个业务之间的序列号
     */
    public RedisSeqBuilder bizName(String bizName) {
        this.bizName = bizName;
        return this;
    }

    /**
     * 可以指定从什么号开始
     */
    public RedisSeqBuilder stepStart(long stepStart) {
        this.stepStart = stepStart;
        return this;
    }

}
